<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/22
 * Time: 11:00
 */
namespace RjgcPay\WxWeChatPay;

use SRjgcWechat\curl\Curl;
use SRjgcWechat\curl\XML;
use SRjgcWechat\message\Message;

class LuckyMoney{

    const APPID = 'wxccce3033a624d942';
    const MCHID = '1487319022';
    const KEY = 'e1dc18a17d3f59f74e5c6a0fea85bfed';
    const APPSECRET = 'e7e6e995e49c9a9c3f050d368189287d';

    const SSLCERT_PATH = '-----BEGIN CERTIFICATE-----
MIIEXzCCA8igAwIBAgIDEN9AMA0GCSqGSIb3DQEBBQUAMIGKMQswCQYDVQQGEwJD
TjESMBAGA1UECBMJR3Vhbmdkb25nMREwDwYDVQQHEwhTaGVuemhlbjEQMA4GA1UE
ChMHVGVuY2VudDEMMAoGA1UECxMDV1hHMRMwEQYDVQQDEwpNbXBheW1jaENBMR8w
HQYJKoZIhvcNAQkBFhBtbXBheW1jaEB0ZW5jZW50MB4XDTE2MDIwMzExNDg1OVoX
DTI2MDEzMTExNDg1OVowgY8xCzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlHdWFuZ2Rv
bmcxETAPBgNVBAcTCFNoZW56aGVuMRAwDgYDVQQKEwdUZW5jZW50MQ4wDAYDVQQL
EwVNTVBheTEkMCIGA1UEAxQb6Ieq5Yqo5YyW5rWL6K+V5ZWG5oi35ZCN56ewMREw
DwYDVQQEEwgxMTM4NDEzMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ALQ/qiPEwzmDLkWQhwA1Td6YQh1BxhgxH244rdpyfiiXv/m/QbYGfkJ27EZiNOkR
tZg0kOh4XGfo99bQwia+SSxPsajtnTwbGOYPKRP4Xc44SlFR9n9v3N5XzLJSXZrv
lKnz3Cf7PdHRTXxs0w0gsubMTu2P0MACLfUw11IPtGisx+SGMlgjGZ20q6suYF+R
ydUTXvHelo9R/HFfyV3RPSZryOHP1CtKMh+H1DOwdwF+d/ZIY2nkdS9HBe3Q2QD1
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18rh85Tf9ghvTvw
4orN7w0pvGTTCNug3fSePpNCNA9bR9e5FwSOkY8hojKc3IOHXjN64WINpKJy1Czm
KOmuH8n2ze0iVPK+jGYmy3FcZ3wFgpYAo3EZcoECgYBWlBWUK3CtT12uoRdepNWg
DCPm0k7KDW71NqiXkA+jxGxsCcv4M3CuN2Xs//2dTWqErhWqMq7ASmfxumCmPHWs
dmjya/fGc6G3IrZNj6/fxPrOLShHDBS1HP/9MmVTBd0d39CaSKBaMzvU3DaJu0rq
d0IqLGwMv/t411orp77J1Q==
-----END PRIVATE KEY-----
';

    //https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack
    const send_redpack='https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack'; //发放普通红包

    //https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack
    const send_groupredpack='https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack';  //发放裂变红包

    //https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo
    const send_gethbinfo='https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo'; //查询红包记录

    /**
     * 获取随机码
     */
    public function getRandCode($num=16){
        $array=array(
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','U','W','X','Y','Z',
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','u','w','x','y','z',
            '1','2','3','4','5','6','7','8','9','0'
        );

        $temstr='';
        $max=count($array);
        for ($i=1;$i<=$num;$i++){
            $key=rand(0,$max-1);
            $temstr.=$array[$key];
        }
        return $temstr;
    }


    public function sendRedpack($data=''){

        $data=[
            'send_name'=>'测试红包',  //商户名称
            're_openid'=>'oEKSg1Q5a4O_JJ4UeN57y_Mj76eE',  //用户openid
            'total_amount'=>0.01,  //付款金额
            'total_num'=>1,   //红包发放总人数
            'wishing'=>'感谢您参加猜灯谜活动，祝您元宵节快乐！',   //红包祝福语
            'act_name'=>'猜灯谜抢红包活动',   //活动名称
            'remark'=>'猜越多得越多，快来抢！',   //备注

            //'scene_id'=>1,   //场景id
            //'risk_info'=>1,   //活动信息
            //'consume_mch_id'=>1,   //资金授权商户号
        ];

        $lucky_data['nonce_str']=$this->getRandCode(32);  //随机字符串 必填

        $lucky_data['mch_billno']=date('YmdHis');  //商户订单号  必填
        $lucky_data['mch_id']=self::MCHID;  //商户号  必填
        $lucky_data['wxappid']=self::APPID;  //公众账号appid  必填

        $lucky_data['send_name']=$data['send_name'];  //商户名称  必填
        $lucky_data['re_openid']=$data['re_openid'];  //用户openid  必填
        $lucky_data['total_amount']=$data['total_amount']*100;  //付款金额  必填
        $lucky_data['total_num']=$data['total_num'];  //红包发放总人数  必填
        $lucky_data['wishing']=$data['wishing'];  //红包祝福语  必填
        $lucky_data['client_ip']=$_SERVER['REMOTE_ADDR'];  //Ip地址  必填
        $lucky_data['act_name']=$data['act_name'];  //活动名称  必填
        $lucky_data['remark']=$data['remark'];  //备注  必填

        //$lucky_data['scene_id']=$data['scene_id'];  //场景id  非必填
        //$lucky_data['risk_info']=$data['risk_info'];  //活动信息  非必填
        //$lucky_data['consume_mch_id']=$data['consume_mch_id'];  //资金授权商户号  非必填


        //签名
        ksort($lucky_data);
        $stringA='';
        foreach ($lucky_data as $k=>$v){
            $stringA.= $k.'='.$v.'&';
        }
        $stringA.='key='.self::KEY;
        $string=strtoupper(md5($stringA));

        //构造方式的xml格式数据
        unset($lucky_data['key']);
        $lucky_data['sign']=$string;//签名  必填
        $xml_dat="";
        $xml_dat.="<xml>".PHP_EOL;
        foreach ($lucky_data as $k=>$v){
            $xml_dat.="<".$k."><![CDATA[".$v."]]></".$k.">".PHP_EOL;
        }
        $xml_dat.="</xml>";

        //执行发送请求及返回xml格式数据处理
        $return_data=$this->postXmlCurl($xml_dat,self::send_redpack,true); //执行curl
        libxml_disable_entity_loader(true);
        $return_data_arr=simplexml_load_string($return_data,'SimpleXMLElement',LIBXML_NOCDATA);

        print_r($return_data_arr);die;

    }


    public function httpPost($url,$post_data,$useCert = false){


        //初使化init方法
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url); //指定URL
        curl_setopt($ch, CURLOPT_POST, 1); //声明使用POST方式来进行发送
        curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:text/xml; charset=utf-8"));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设定请求后返回结果 获取的信息以文件流的形式返回
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //发送什么数据呢


        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); ///严格校验
        if($useCert == true){

            $ssl_dir=dirname(__FILE__).'/cert';
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            //curl_setopt($ch,CURLOPT_SSLCERT, self::SSLCERT_PATH);
            curl_setopt($ch,CURLOPT_SSLCERT, $ssl_dir.'apiclient_cert.pem');
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            //curl_setopt($ch,CURLOPT_SSLKEY, self::SSLKEY_PATH);
            curl_setopt($ch,CURLOPT_SSLKEY, $ssl_dir.'apiclient_key.pem');
        }


        curl_setopt($ch, CURLOPT_HEADER, 0); //忽略header头信息
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时时间

        $output = curl_exec($ch); //发送请求
        curl_close($ch); //关闭curl

        //返回数据
        return $output;
    }


    private function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验

        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if($useCert == true){
            $ssl_dir=dirname(__FILE__).'/cert';
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            //curl_setopt($ch,CURLOPT_SSLCERT, self::SSLCERT_PATH);
            curl_setopt($ch,CURLOPT_SSLCERT, $ssl_dir.'apiclient_cert.pem');
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            //curl_setopt($ch,CURLOPT_SSLKEY, self::SSLKEY_PATH);
            curl_setopt($ch,CURLOPT_SSLKEY, $ssl_dir.'apiclient_key.pem');
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);

        print_r($data);die;

        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new \Exception("curl出错，错误码:$error");
        }
    }

}